//
//  TSFindSceneViewModel.m
//  TaShuo
//
//  Created by N-X on 2018/3/19.
//  Copyright © 2018年 MRNAN. All rights reserved.
//

#import "TSFindSceneViewModel.h"
#import "TSFindCategoryCell.h"
#import "TSFindSpecialCell.h"
#import "TSFindActivityCell.h"
#import "TSFindBusinessAreaCell.h"
#import "TSFindRecommendCell.h"
#import "TSFindCategoryModel.h"
#import "TSFindSectionHeaderView.h"
#import "TSFindCategoryCellViewModel.h"
#import "TSFindCategoryItemViewModel.h"
#import "TSFindActivityModel.h"
#import "TSFindActivityCellViewModel.h"
#import "TSFindAcrivityItemViewModel.h"
#import "TSFindTopicModel.h"
#import "TSFindTopicCellViewModel.h"
#import "TSFindTopicItemViewModel.h"
#import "TSFindBusinessModel.h"
#import "TSFindBusinessCellViewModel.h"
#import "TSFindBusinessItemViewModel.h"
#import "TSFindRecommendModel.h"
#import "TSFindRecommendCellViewModel.h"


@interface TSFindSceneViewModel()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong)NSMutableArray * categoryDatas;
@property (nonatomic ,strong)NSMutableArray * activityDatas;
@property (nonatomic ,strong)NSMutableArray * topicDatas;
@property (nonatomic ,strong)NSMutableArray * businessDatas;
@property (nonatomic ,strong)NSMutableArray * recommendDatas;
@end
@implementation TSFindSceneViewModel

#pragma mark

- (instancetype)init
{
    if (self = [super init]) {
        _categoryDatas = [NSMutableArray array];
        _activityDatas = [NSMutableArray array];
        _topicDatas = [NSMutableArray array];
        _businessDatas = [NSMutableArray array];
        _recommendDatas = [NSMutableArray array];
    }
    return self;
}

#pragma mark - getter

- (RACCommand *)fetchFindDataCommand
{
    if (!_fetchFindDataCommand) {
        
        _fetchFindDataCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            RACSignal * bannerSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                [subscriber sendNext:@"banner"];
                [subscriber sendCompleted];
                return nil;
            }];
            
            RACSignal * categorySignal = [self requestCategoryData];
            RACSignal * topicSignal = [self requestTopicData];
            RACSignal * activitySignal = [self requestActivityData];
            RACSignal * businessSignal = [self requestBusinessData];
            RACSignal * recommendSignal = [self requestRecommendData];
            RACSignal * signal = [RACSignal combineLatest:@[bannerSignal,categorySignal,topicSignal,activitySignal,businessSignal,recommendSignal]];
            return signal;
        }];
    }
    return _fetchFindDataCommand;
}

#pragma mark - 请求数据

- (RACSignal *)requestCategoryData
{
    RACSignal * categorySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[TSNetTools sharedTSNetTools] GET:@"https://www.yohomars.com/api/v1/store/store/category?app_version=2.2.6&client_secret=548ae90fc32966ad07a52a3bc98835de&client_type=iphone&lang=zh&latitude=31.671967&longitude=119.953293&model=iPhone10%2C2&os_version=11.2.6&screen_size=414x736&session_code=a97cbc53113334edc9b42e56c1e6e08c&udid=221198c14e9656e3b4f4fe080617b20e691cfe34&unique_token=221198c14e9656e3b4f4fe080617b20e691cfe34&v=1" params:nil isShowProgress:NO completion:^(NSError *error, id responseJson, BOOL isCache) {
            if (!error) {
                NSInteger code = [responseJson[@"code"] integerValue];
                if (code == 200) {
                    NSArray * dataArray = responseJson[@"data"];
                    NSArray * resultArray = [[[TSFindCategoryModel mj_objectArrayWithKeyValuesArray:dataArray].rac_sequence map:^id _Nullable(id  _Nullable value) {
                        TSFindCategoryItemViewModel * itemVM = [[TSFindCategoryItemViewModel alloc]init];
                        itemVM.categoryCellModel = value;
                        return itemVM;
                    }] array];
                    TSFindCategoryCellViewModel * cellVM = [[TSFindCategoryCellViewModel alloc]init];
                    cellVM.items = resultArray;
                    [self.categoryDatas addObject:cellVM];
                    
                    
                    [subscriber sendNext:self.categoryDatas];
                    [subscriber sendCompleted];
                }
                
            }else
            {
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
    return categorySignal;
}

- (RACSignal *)requestTopicData
{
    RACSignal * topicSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[TSNetTools sharedTSNetTools] GET:@"https://www.yohomars.com/api/v2/topic/topic/topicindex?app_version=2.2.6&city_id=5176&client_secret=99cf972ad2dbb980a4284662626d0416&client_type=iphone&lang=zh&latitude=31.671748&limit=5&longitude=119.953249&model=iPhone10%2C2&os_version=11.2.6&page=1&rand=1&screen_size=414x736&session_code=a97cbc53113334edc9b42e56c1e6e08c&udid=221198c14e9656e3b4f4fe080617b20e691cfe34&unique_token=221198c14e9656e3b4f4fe080617b20e691cfe34&v=2" params:nil isShowProgress:NO completion:^(NSError *error, id responseJson, BOOL isCache) {
            if (!error) {
                NSInteger code = [responseJson[@"code"] integerValue];
                if (code == 200) {
                    NSDictionary * dataDict = responseJson[@"data"];
                    NSArray * listArray = dataDict[@"list"];
                    NSArray * result = [[[TSFindTopicModel mj_objectArrayWithKeyValuesArray:listArray].rac_sequence map:^id _Nullable(id  _Nullable value) {
                        TSFindTopicItemViewModel * itemVM = [[TSFindTopicItemViewModel alloc]init];
                        itemVM.topicItem = value;
                        return itemVM;
                    }] array];
                    TSFindTopicCellViewModel * cellVM = [[TSFindTopicCellViewModel alloc]init];
                    cellVM.topicItems = result;
                    [self.topicDatas addObject:cellVM];
                    [subscriber sendNext:self.topicDatas];
                    [subscriber sendCompleted];
                }
                
            }else
            {
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
    return topicSignal;
}

- (RACSignal *)requestActivityData
{
    RACSignal * activitySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[TSNetTools sharedTSNetTools] GET:@"https://www.yohomars.com/yohomars/TblActivityPrevRest/getActivityProdList?app_version=2.2.6&catid=&cityId=5176&client_secret=4deadeb2bacbdb668d550fa09bcfcc0c&client_type=iphone&endTime=&lang=zh&latitude=31.671967&limit=4&longitude=119.953293&model=iPhone10%2C2&os_version=11.2.6&page=1&screen_size=414x736&session_code=a97cbc53113334edc9b42e56c1e6e08c&startTime=&udid=221198c14e9656e3b4f4fe080617b20e691cfe34&uid=54061068&unique_token=221198c14e9656e3b4f4fe080617b20e691cfe34&v=2" params:nil isShowProgress:NO completion:^(NSError *error, id responseJson, BOOL isCache) {
            if (!error) {
                NSInteger code = [responseJson[@"code"] integerValue];
                if (code == 200) {
                    NSDictionary * dataDict = responseJson[@"data"];
                    NSArray * rows = dataDict[@"rows"];
                    NSArray * result = [[[TSFindActivityModel mj_objectArrayWithKeyValuesArray:rows].rac_sequence map:^id _Nullable(id  _Nullable value) {
                        TSFindAcrivityItemViewModel * itemVM = [[TSFindAcrivityItemViewModel alloc]init];
                        itemVM.itemModel = value;
                        return itemVM;
                    }] array];
                    TSFindActivityCellViewModel * cellVM = [[TSFindActivityCellViewModel alloc]init];
                    cellVM.activityItems = result;
                    [self.activityDatas addObject:cellVM];
                    
                    [subscriber sendNext:self.activityDatas];
                    [subscriber sendCompleted];
                }
            }else
            {
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
    return activitySignal;
}

- (RACSignal *)requestBusinessData
{
    RACSignal * businessSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[TSNetTools sharedTSNetTools] GET:@"https://www.yohomars.com/api/v1/bizarea/bizareas/bizlist?app_version=2.2.6&city_id=5176&client_secret=320c1b1dc9596284948b0a4a35ef95a3&client_type=iphone&lang=zh&latitude=31.671967&limit_1=9&limit_2=10&longitude=119.953293&model=iPhone10%2C2&os_version=11.2.6&page=1&screen_size=414x736&session_code=a97cbc53113334edc9b42e56c1e6e08c&show_stores=0&udid=221198c14e9656e3b4f4fe080617b20e691cfe34&unique_token=221198c14e9656e3b4f4fe080617b20e691cfe34&v=1" params:nil isShowProgress:NO completion:^(NSError *error, id responseJson, BOOL isCache) {
            if (!error) {
                NSInteger code = [responseJson[@"code"] integerValue];
                if (code == 200) {
                    NSDictionary * dataDict = responseJson[@"data"];
                    NSArray * listArray = dataDict[@"list"];
                    NSArray * result = [[[TSFindBusinessModel mj_objectArrayWithKeyValuesArray:listArray].rac_sequence map:^id _Nullable(id  _Nullable value) {
                        TSFindBusinessItemViewModel * itemVM = [[TSFindBusinessItemViewModel alloc]init];
                        itemVM.itemModel = value;
                        return itemVM;
                    }] array];
                    TSFindBusinessCellViewModel * cellVM = [[TSFindBusinessCellViewModel alloc]init];
                    cellVM.businessItems = result;
                    [self.businessDatas addObject:cellVM];
                    [subscriber sendNext:self.businessDatas];
                    [subscriber sendCompleted];
                }
            }else
            {
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
    return businessSignal;
}

- (RACSignal *)requestRecommendData
{
    RACSignal * recommendSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [[TSNetTools sharedTSNetTools] GET:@"https://www.yohomars.com/api/v2/store/store/recommendStore?app_version=2.2.6&city_id=5176&client_secret=fb5fff199871f00eab8490f7444bfa7b&client_type=iphone&lang=zh&latitude=31.671748&longitude=119.953249&model=iPhone10%2C2&os_version=11.2.6&screen_size=414x736&session_code=a97cbc53113334edc9b42e56c1e6e08c&udid=221198c14e9656e3b4f4fe080617b20e691cfe34&unique_token=221198c14e9656e3b4f4fe080617b20e691cfe34&v=2" params:nil isShowProgress:NO completion:^(NSError *error, id responseJson, BOOL isCache) {
            if (!error) {
                
                NSInteger code = [responseJson[@"code"] integerValue];
                if (code == 200) {
                    NSArray * dataArray = responseJson[@"data"];
                    NSArray * result = [[[TSFindRecommendModel mj_objectArrayWithKeyValuesArray:dataArray].rac_sequence map:^id _Nullable(id  _Nullable value) {
                        TSFindRecommendCellViewModel * cellVM = [[TSFindRecommendCellViewModel alloc]init];
                        cellVM.model = value;
                        return cellVM;
                    }] array];
                    self.recommendDatas = [result mutableCopy];
                    [subscriber sendNext:self.recommendDatas];
                    [subscriber sendCompleted];
                }
            }else
            {
                [subscriber sendError:error];
            }
        }];
        return nil;
    }];
    return recommendSignal;
}

#pragma mark - TSViewModelProtocol 绑定view

- (void)bindView:(UIView *)view
{
    UITableView * tableView = (UITableView *)view;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = NX_ColorFromRGB(88, 109, 76);
    //创建headerView
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 100)];
    headerView.backgroundColor = [UIColor purpleColor];
    tableView.tableHeaderView = headerView;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //注册cell
    [tableView registerClass:[TSFindCategoryCell class] forCellReuseIdentifier:kFindCategoryCellID];
    [tableView registerClass:[TSFindSpecialCell class] forCellReuseIdentifier:kFindSpecialCellID];
    [tableView registerClass:[TSFindActivityCell class] forCellReuseIdentifier:kFindActivityCellID];
    [tableView registerClass:[TSFindBusinessAreaCell class] forCellReuseIdentifier:kFindBusinessAreaCellID];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TSFindRecommendCell class]) bundle:nil] forCellReuseIdentifier:kFindRecommendCellID];
    
}

#pragma mark - UITableViewDelegate && UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 4:
            
            return self.recommendDatas.count;
            
        default:
            return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    switch (indexPath.section) {
        case 0:
        {
            TSFindCategoryCell * cell = [tableView dequeueReusableCellWithIdentifier:kFindCategoryCellID];
            if (self.categoryDatas.count) {
                TSFindCategoryCellViewModel * cellVM = self.categoryDatas[indexPath.row];
                [cellVM bindView:cell.collectionView];
            }
            cell.backgroundColor = [UIColor yellowColor];
            return cell;
        }
        case 1:
        {
            TSFindSpecialCell * cell = [tableView dequeueReusableCellWithIdentifier:kFindSpecialCellID];
            if (self.topicDatas.count) {
                TSFindTopicCellViewModel * cellVM = self.topicDatas[indexPath.row];
                [cellVM bindView:cell.collectionView];
            }
            cell.backgroundColor = [UIColor whiteColor];
            return cell;
        }
        case 2:
        {
            TSFindActivityCell * cell = [tableView dequeueReusableCellWithIdentifier:kFindActivityCellID];
            if (self.activityDatas.count) {
                TSFindActivityCellViewModel * cellVM = self.activityDatas[indexPath.row];
                [cellVM bindView:cell.collectionView];
            }
            return cell;
        }
        case 3:
        {
            TSFindBusinessAreaCell * cell = [tableView dequeueReusableCellWithIdentifier:kFindBusinessAreaCellID];
            if (self.businessDatas.count) {
                TSFindBusinessCellViewModel * cellVM = self.businessDatas[indexPath.row];
                [cellVM bindView:cell.collectionView];
            }
            return cell;
        }
        case 4:
        {
            TSFindRecommendCell * cell = [tableView dequeueReusableCellWithIdentifier:kFindRecommendCellID];
            if (self.recommendDatas.count) {
                TSFindRecommendCellViewModel * cellVM = self.recommendDatas[indexPath.row];
                [cellVM bindView:cell];
            }
            return cell;
        }

    }
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return 180;
        }
        case 1:
        {
            return 200;
        }
        case 2:
        {
            return 400;
        }
        case 3:
        {
            return 140;
        }
        case 4:
        {
            return 372;
        }
    }
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TSFindSectionHeaderView * header = [TSFindSectionHeaderView NX_ViewFromXib];
    header.frame = CGRectMake(0, 0, KScreenWidth, 35);

    if (section == 2) {
       
    }
    switch (section) {
        case 2:
        {
            header.titleLabel.text  = @"活动";
            return header;
        }
        case 3:
        {
            header.titleLabel.text  = @"商圈";
            return header;
        }
        case 4:
        {
            header.titleLabel.text = @"猜你喜欢";
            header.moreButton.hidden = YES;
            return header;
        }
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2 || section == 3 || section == 4) {
        return 35;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

// 要想去掉分组头/尾的高度，将分组头/尾的高度设置为 0.01（不能设为 0，否则无效）。同时还要将分组尾设置成一个空的 UIView（否则在 iOS11 下分组尾高度不会起作用）
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

@end
